/**
 * Created by hjx on 2017/7/26.
 */
/*创建了一个集合*/
Posts = new Mongo.Collection('posts');

// 允许创建者删除帖子
Posts.allow({
    remove: function(userId, post) { return ownsDocument(userId, post); }
});

// 限制创建者编辑帖子的字段
/*Posts.deny({
    update: function(userId, post, fieldNames) {
        // 只能更改如下两个字段：；_.without()是使用了Underscore库，返回一个数组不含设定的字段，在这里
        //如果数组长度大于1，则返回true 限制更新
        return (_.without(fieldNames, 'url', 'title').length > 0);
    }
});*/

Meteor.methods({
    /*定义添加方法*/
    postInsert: function(postAttributes) {
        check(Meteor.userId(), String);
        check(postAttributes, {
            title: String,
            url: String
        });

        /*检查空值*/
        var errors = validatePost(postAttributes);
        if (errors.title || errors.url)
            throw new Error.throw("你必须为你的帖子填写标题和 URL");

        /*检查重复*/
        var postWithSameLink = Posts.findOne({url: postAttributes.url});
        if (postWithSameLink) {
            return {
                postExists: true,
                _id: postWithSameLink._id
            }
        }

        /*延伸postAttributes的属性*/
        var user = Meteor.user();
        var post = _.extend(postAttributes, {
            userId: user._id,
            author: user.username,
            submitted: new Date()
        });

        var postId = Posts.insert(post);

        return {
            _id: postId
        };
    },

    /*定义更新方法*/
    postUpdate: function(currentPostId, postProperties) {
        check(currentPostId, String);
        check(postProperties, {
            title: String,
            url: String
        });

        /*检查空值*/
        var errors = validatePost(postProperties);
        if (errors.title || errors.url)
            throw new Error.throw("你必须为你的帖子填写标题和 URL");

        /*检查重复*/
        var postWithSameLink = Posts.findOne({url: postProperties.url});
        var oldLink = Posts.findOne({_id: currentPostId});
            if (postWithSameLink && postWithSameLink.url!=oldLink.url) {
                return {
                    postExists: true,
                    _id: postWithSameLink._id
                }
        }
        /*更新编辑时间*/
        var post = _.extend(postProperties, {
            submitted: new Date()
        });
        Posts.update(currentPostId, {$set: postProperties});
        return {
            _id: currentPostId
        };
    }

});

/*判断字段是否为空*/
validatePost = function (post) {
    var errors = {};

    if (!post.title)
        errors.title = "请填写标题";

    if (!post.url)
        errors.url =  "请填写 URL";

    return errors;
}
